/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}

/**
 * 计算当前时间与天数相减得到的时间
 * @param time 当前时间
 * @param days 天数
 */
export function subtractTheNumberOfDays(time, days) {
  //可以加上错误处理
  var a = new Date(time)
  a = a.valueOf()
  a = a - days * 24 * 60 * 60 * 1000
  a = new Date(a)
  /**
   * xx-xx-xx
   */
  let day = a.getFullYear() +"" + (a.getMonth() + 1 < 10 ? '0' + (a.getMonth() + 1) : a.getMonth() + 1) +""+ (a.getDate()>10?a.getDate():"0"+a.getDate())+''
  /**
   * xx年xx月xx日
   */
  let day_zh = a.getFullYear() + "年" + (a.getMonth() + 1) + "月" + a.getDate() + "日"

  /**
   * 20200909
   */
  let day_ = a.getFullYear() + "-" + (a.getMonth() + 1) + "-" + a.getDate()
  return {
    day: day,
    day_zh: day_zh,
    day_: day_,
  }
}
/**
 * 判断时间是当前周还是上一周几
 * @param time
 * @returns {{ isLastWeek,isThisWeek,Week,titleTime: string, titleDate: string}}
 */
export function isWeek(time) {

  // 当前时间
  var timestamp = Date.parse(new Date());
  var serverDate = new Date(timestamp);

  //本周周日的的时间
  var sundayTiem = timestamp + ((7 - serverDate.getDay()) * 24 * 60 * 60 * 1000)
  var SundayData = new Date(sundayTiem);
  //年
  var tomorrowY = SundayData.getFullYear();
  //月
  var tomorrowM = (SundayData.getMonth() + 1 < 10 ? '0' + (SundayData.getMonth() + 1) : SundayData.getMonth() + 1);
  //日
  var tomorrowD = SundayData.getDate() < 10 ? '0' + SundayData.getDate() : SundayData.getDate();
  // console.log(tomorrowY + '-' + tomorrowM + '-' + tomorrowD);

  // 本周周一的时间
  var mondayTime = timestamp - ((serverDate.getDay() - 1) * 24 * 60 * 60 * 1000)
  var mondayData = new Date(mondayTime);
  //年
  var mondayY = mondayData.getFullYear();
  //月
  var mondayM = (mondayData.getMonth() + 1 < 10 ? '0' + (mondayData.getMonth() + 1) : mondayData.getMonth() + 1);
  //日
  var mondayD = mondayData.getDate() < 10 ? '0' + mondayData.getDate() : mondayData.getDate();
  // console.log(mondayY + '-' + mondayM + '-' + mondayD);


  // 当前时间
  var currentData = new Date(time);
  //年
  var currentY = currentData.getFullYear();
  //月
  var currentM = (currentData.getMonth() + 1 < 10 ? '0' + (currentData.getMonth() + 1) : currentData.getMonth() + 1);
  //日
  var currentD = currentData.getDate() < 10 ? '0' + currentData.getDate() : currentData.getDate();
  //时
  var currenH = currentData.getHours();
  //分
  var currenM = currentData.getMinutes();
  var str = "星期" + "日一二三四五六".charAt(currentData.getDay());

  var sundayDay = tomorrowY + tomorrowM + tomorrowD;
  var mondayDay = mondayY + mondayM + mondayD;
  var currentDay = currentY + currentM + currentD;

  var sundayDay_ = `${tomorrowY}-${tomorrowM}-${tomorrowD}`.trim();
  var mondayDay_ = `${mondayY}-${mondayM}-${mondayD}`.trim();
  var currentDay_ = `${currentY}-${currentM}-${currentD}`.trim();
  // console.log('本周日:' + sundayDay_ + ',本周一:' + mondayDay_ + ',当前时间：' + currentDay_)
  parseInt(currentDay);
  parseInt(mondayDay);
  if (parseInt(currentDay) >= parseInt(mondayDay)) {
    if (parseInt(currentDay) <= parseInt(sundayDay)) {
      console.log('是本周')
      return {
        Week: str,
        titleDate: ' ' + currentM + '/' + currentD + ' ',
        titleTime: currenH + ':' + currenM,
        //是否为本周
        isThisWeek:true,
        //是否为上一周
        isLastWeek:false
      }
    } else {
      console.log('本周后')
      return {
        titleDate: ' ' + currentM + '/' + currentD + ' ',
        Week: '本周之后'+str,
        titleTime: currenH + ':' + currenM,
        //是否为本周
        isThisWeek:false,
        //是否为上一周
        isLastWeek:false
      }
    }
  } else {
    console.log("上周")
    //上周日
    let sunday = subtractTheNumberOfDays(sundayDay_,7);
    //上周一
    let monday = subtractTheNumberOfDays(mondayDay_,7);
    if (parseInt(currentDay) >= parseInt(monday.day)) {
        if (parseInt(currentDay) <= parseInt(sunday.day)) {
        // console.log("上周日" + sunday.day)
        // console.log("上周一" + monday.day)
        return {
          Week: '上周' + str,
          titleDate: ' ' + currentM + '/' + currentD + ' ',
          titleTime: currenH + ':' + currenM,
          //是否为本周
          isThisWeek:false,
          //是否为上一周
          isLastWeek:true
        }
      }
    }else {
      return {
        Week: '上上周之前' + str,
        titleDate: ' ' + currentM + '/' + currentD + ' ',
        titleTime: currenH + ':' + currenM,
        //是否为本周
        isThisWeek:false,
        //是否为上一周
        isLastWeek:false
      }
    }
  }
}
